<template>
  <VPage>
    <VTable ref="tableRef" v-bind="tableOptins">
      <template #form="{ form }">
        <XForm
          :fieldList="fieldList"
          :formOption="optionsDataAll"
          :formData="form"
        >
          <template #create_user="{ value, input }">
            <VCascader
              :model-value="value"
              @update:model-value="input"
              collapse-tags
              class="w-[200px]"
              placeholder="创建人"
            />
          </template>
        </XForm>
      </template>
      <template #toolbar_btns>
        <VActionBar :actions="actions" />
      </template>
      <template #tc_numbers="{ row }">
        <template v-for="(i, idx) in row?.tc_numbers || []" :key="i">
          <div v-if="idx < 1">{{ i }}</div>
        </template>
        <div class="text-left">
          <el-text
            type="primary"
            class="cursor-pointer text-[#3487FF]"
            v-if="row?.tc_numbers?.length > 1"
            @click="
              numberDialogRef?.open({
                data: row.tc_numbers,
                title: '头程备库单号',
              })
            "
            >更多信息</el-text
          >
        </div>
      </template>
      <template #fba_ids="{ row }">
        <template v-for="(i, idx) in row?.fba_ids || []" :key="i">
          <div v-if="idx < 1">{{ i }}</div>
        </template>
        <div class="text-left">
          <el-text
            type="primary"
            class="cursor-pointer text-[#3487FF]"
            v-if="row?.fba_ids?.length > 1"
            @click="
              numberDialogRef?.open({
                data: row.fba_ids,
                title: 'FBAID',
              })
            "
            >更多信息</el-text
          >
        </div>
      </template>
      <template #ph_number="{ row }">
        <template v-for="(i, idx) in row?.ph_number || []" :key="i">
          <div v-if="idx < 1">{{ i }}</div>
        </template>
        <div class="text-left">
          <el-text
            type="primary"
            class="cursor-pointer text-[#3487FF]"
            v-if="row?.ph_number?.length > 1"
            @click="
              numberDialogRef?.open({
                data: row.ph_number,
                title: '配货单号',
              })
            "
            >更多信息</el-text
          >
        </div>
      </template>
      <template #operation="{ row }">
        <div>
          <el-button
            link
            v-if="row.is_gen == 1"
            type="primary"
            @click="handleInvoice(row.id)"
            v-hasPermi="[exportRebatesAuthList.invoice_download.download]"
          >
            下载发票
          </el-button>
          <el-button
            link
            v-if="row.is_cancel != '是'"
            type="danger"
            @click="handleCancel(row.id)"
            v-hasPermi="[exportRebatesAuthList.invoice_download.cancel]"
          >
            作废
          </el-button>
          <el-button link type="primary" @click="handleLog(row)">
            日志
          </el-button>
        </div>
      </template>
    </VTable>
    <numberDialog ref="numberDialogRef" />
    <SpecialLog
      dialog
      v-model="logVisible"
      :autoLoad="false"
      tag="CLS_INVOICE"
      :business_id="logId"
      @close="logId = ''"
    />
    <DerivedCenter ref="DerivedCenterRef"></DerivedCenter>
  </VPage>
</template>
<script setup lang="jsx">
import { ElMessage } from "element-plus";
import XForm from "@/components/XForm/index.vue";
import { exportRebatesAuthList } from "@/Auth/export-rebates.js";
import numberDialog from "@/components/numberDialog/index.vue";
import {
  clsInvoiceList,
  clsInvoiceCancel,
  clsInvoiceDownload,
  clsInvoiceGenInvoice,
} from "./api.js";
import { getChannelList, logisticsList } from "@/api/index.js";
import { handleLink, getTableSelect, tipMessage } from "@/hooks/tool.js";
import SpecialLog from "@/components/SpecialLog/index.vue";
import { downloadAndZipFiles } from "@/utils/zipUtils.js";
import { formatTime } from "@/utils/time.js";
import DerivedCenter from "@/components/DerivedCenter/index.vue";
import { getTableSelectRow } from "@/hooks/tool.js";
import { config_name } from "@/config/export.js";
import { useEnumSelect } from "@/hooks";
const { proxy } = getCurrentInstance();
const tableRef = ref();
const numberDialogRef = ref();
const tableOptins = reactive({
  formConfig: {
    data: {
      create_user: "",
      dateRange: { type: "create_time", value: [], range: false }, // 组合+日期范围
    },
  },
  tooltipConfig: {
    showAll: false,
  },
  isToggle: true,
  columns: [
    { fixed: "left", width: 50, type: "checkbox" },
    {
      fixed: "left",
      title: "清关发票单号",
      minWidth: 160,
      field: "cls_invoice_no",
    },
    {
      title: "头程备库单号",
      fixed: "left",
      minWidth: 200,
      slots: { default: "tc_numbers" },
    },
    {
      title: "配货单号",
      minWidth: 200,
      slots: { default: "ph_number" },
    },
    {
      title: "FBAID",
      minWidth: 200,
      slots: { default: "fba_ids" },
    },
    { title: "备库类型", width: 160, field: "tc_dc_type" },
    { title: "物流商", width: 260, field: "logistics_name" },
    { title: "渠道", width: 160, field: "channel_name" },
    { title: "创建人员", width: 160, field: "create_user" },
    { title: "生成时间", width: 160, field: "gen_time" },
    { title: "是否作废", width: 120, field: "is_cancel" },
    { title: "发票状态", width: 120, field: "gen_status" },
    {
      title: "失败原因",
      width: 250,
      field: "gen_errors",
      slots: {
        default: ({ row }) => {
          let errors = row?.gen_errors?.join("\n");
          return <VText value={errors} line={2} />;
        },
      },
    },
    {
      title: "操作",
      field: "",
      fixed: "right",
      width: 180,
      slots: { default: "operation" },
    },
  ],
  proxyConfig: {
    autoLoad: false, // 是否自动加载查询数据
    props: {
      result: "data",
      total: "total",
    },
    ajax: {
      query: ({ page, form }) => {
        return clsInvoiceList({ ...form, ...page }).then((res) => {
          return {
            data: res.data,
            total: res.total,
          };
        });
      },
    },
  },
});
const optionsData1 = ref({});
//获取物流商
const getlogistics = () => {
  logisticsList({}).then((res) => {
    optionsData1.value.logistics = res?.data || [];
  });
};
getlogistics();
const getChannel = async () => {
  const { data } = await getChannelList();
  optionsData1.value.channel = data;
};
getChannel();
const { options: optionsData } = useEnumSelect({
  params: ["cls_invoice_cancel_type"],
});
const optionsDataAll = computed(() =>
  Object.assign({}, optionsData.value, optionsData1.value)
);
const handleCancel = (id) => {
  handleCancelReq(id);
};
const handleCancelReq = (id) => {
  proxy?.confirm({
    title: "提示",
    content: (
      <p>
        确认废除选中的
        <span class="text-[#3366F1] px-[4px]">{id.length || 1}</span>
        条数据？
      </p>
    ),
    beforeClose: async (action, instance, done) => {
      if (action === "confirm") {
        try {
          instance.confirmButtonLoading = true;
          instance.confirmButtonText = "处理中..";
          const { code, data, message } = await clsInvoiceCancel({ id });
          if (code != 200) return ElMessage.error(message);
          tipMessage(data);
        } catch (e) {
          console.error(e);
        } finally {
          instance.confirmButtonLoading = false;
          done();
          refresh();
        }
      } else {
        done();
      }
    },
  });
};
const handleBatchCancel = () => {
  let records = tableRef.value?.$table?.getCheckboxRecords() || [];
  if (!records?.length) return ElMessage.warning("请至少选择一条数据!");
  let is_cancel = records.some((record) => record.is_cancel !== "是");
  if (!is_cancel) return ElMessage.warning("请至少选择一条没有废除的数据!");
  let rows = records?.map((item) => item.id);
  handleCancelReq(rows);
};
const handleInvoice = async (id) => {
  const { data, code, message } = await clsInvoiceDownload({ id });
  if (code != 200) return ElMessage.error(message);
  handleLink(data?.invoice_link?.[0]);
};

const logId = ref("");
const logVisible = ref(false);
const handleLog = (item) => {
  logId.value = item.id;
  logVisible.value = true;
};
const refresh = () => {
  tableRef?.value.$table.commitProxy("query");
};
const fieldList = [
  {
    field: "numberNo",
    placeholder: "请输入",
    select: [
      { label: "清关发票号", value: "cls_invoice_no" },
      { label: "头程备库单号", value: "tc_numbers" },
      { label: "配货单号", value: "ph_number" },
      { label: "FBAID", value: "fba_ids" },
    ],
    itemProps: {
      type: "textarea",
      autosize: { minRows: 1, maxRows: 2 },
    },
    selectStyle: { width: "130px" },
    type: "input",
    style: { width: "240px" },
  },
  {
    field: "logistics_id",
    type: "select",
    options: {
      placeholder: "物流商名称",
      labelKey: "logistics_name",
      valueKey: "logistics_id",
    },
    class: "select-wrapper-style",
    originOption: "logistics",
    style: { width: "240px" },
    collapseTags: true,
    multiple: true,
  },
  {
    field: "channel_id",
    type: "select",
    style: { width: "180px" },
    originOption: "channel",
    options: {
      placeholder: "物流商渠道中文名",
      labelKey: "channel_name",
      valueKey: "channel_id",
    },
  },
  {
    field: "tc_dc_type",
    type: "select",
    options: {
      placeholder: "备库类型",
      data: [
        { label: "FBA备库单", value: "1" },
        { label: "海外仓备库单", value: "2" },
      ],
    },
    style: { width: "120px" },
  },
    {
    field: "is_cancel",
    type: "select",
    options: {
      placeholder: "是否作废",
    },
    originOption: "cls_invoice_cancel_type",
    style: { width: "120px" },
  },
  {
    field: "create_user",
    slot: "create_user",
  },
  {
    field: "dateRange",
    type: "dateTimeRange",
    style: { width: "360px" },
    selectStyle: { width: "100px" },
    select: [{ label: "生成日期", value: "create_time" }],
    itemProps: {
      startPlaceholder: "创建最早时间",
      endPlaceholder: "创建最晚时间",
    },
  },
];
const handlebachInvoice = async () => {
  let rows = getTableSelect(tableRef.value);
  if (!rows?.length) return ElMessage.warning("请至少选择一条数据!");
  const { data, code, message } = await clsInvoiceDownload({ id: rows });
  if (code != 200) return ElMessage.error(message);
  try {
    let time = formatTime(null, "YYYYMMDD");
    await downloadAndZipFiles(data?.invoice_link || [], time + "发票");
    console.log("ZIP 文件导出成功");
  } catch (error) {
    console.error("导出 ZIP 文件失败", error);
  }
  // const links = data?.invoice_link || [];
  // for (const item of links) {
  //   handleLink(item);
  //   await new Promise((resolve) => setTimeout(resolve, 500));
  // }
};
const handlebachProInvoice = async () => {
  let rows = getTableSelect(tableRef.value);
  if (!rows?.length) return ElMessage.warning("请至少选择一条数据!");
  const { code, data, message } = await clsInvoiceGenInvoice({ id: rows });
  if (code != 200) return ElMessage.error(message);
  tipMessage(data);
  refresh();
};

//导出中心
const DerivedCenterRef = ref();
const handleExport = async () => {
  let condition = getTableSelectRow(tableRef.value);
  DerivedCenterRef.value.open({
    tag_name: config_name["export_rebates"]["cls_invoices_export"],
    condition,
  });
};
const actions = ref([
  {
    label: "批量下载发票",
    fn: handlebachInvoice,
    type: "primary",
    permission: [exportRebatesAuthList.invoice_download.download],
  },
  {
    label: "批量生成发票",
    fn: handlebachProInvoice,
    type: "primary",
    permission: [exportRebatesAuthList.invoice_download.create],
  },
  {
    label: "批量作废",
    fn: handleBatchCancel,
    type: "danger",
    permission: [exportRebatesAuthList.invoice_download.cancel],
  },
  {
    label: "导出",
    dkicon: "icon-Upload",
    right: true,
    fn: handleExport,
    permission: [exportRebatesAuthList.invoice_download.export],
  },
]);
</script>
<style lang="scss" scoped></style>
